package com.zengqingfa.basic.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @fileName: ReflectTest2
 * @author: zengqf3
 * @date: 2021-6-23 11:02
 * @description:
 */
public class ReflectTest2 {

    public static void main(String[] args) throws Exception {
        Property property = new Property();
        Field field = Property.class.getDeclaredField("value");
        //方式一：使用java.lang.reflect.Field.set(Object obj, Object value)
        field.setAccessible(true);
        field.set(property, "val1");
        System.out.println(property);
        //方式二：通过调用属性的set方法来完成赋值。
        Class clazz = property.getClass();
        Method method = clazz.getMethod("setValue", String.class);
        String param = "val222";
        method.invoke(property, param);
        System.out.println(property);

    }
}


class Property {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        System.out.println("set value");
        this.value = value;
    }

    @Override
    public String toString() {
        return "Property{" +
                "value='" + value + '\'' +
                '}';
    }
}